<template>
  <div class="pagewrapper p-20 pb-10 flexcolumn">
    <div class="bg_fff p-12 wc_top w-full mb-16 flexbetween">
      <div>
        <span class="c_text3 f-14"
          >套餐总席位：<span class="c_text2">1</span></span
        >
        <span class="c_text3 f-14 ml-32"
          >总在线：<span class="c_text2">0</span></span
        >
      </div>
      <el-button type="primary" plain>待验证企微号(0)</el-button>
    </div>
    <div class="wc_wraaper flex">
      <div class="wc_left bg_fff h_full">
        <div class="wl_header flexbetween">
          <span class="c_text2">分组</span>
          <div v-hasPermi="['system:tgwechat:addgroup']" class="commhover p-6 plusbtn f-16 c_primary">
            <i class="el-icon-plus" @click="handleAdd"></i>
          </div>
        </div>
        <div class="wl_content p-12">
          <!-- <div @click="handleItem({id:''})" 
            class="w_full wl_item commhover flex aligncenter mb-6 f-14"
            :class="{active:activeId==''}"
          >
            <svg-icon class-name="mr-8 f-14" icon-class="icontent" />
            <span class="wl_text">全部</span>
            <span class="pl-8 c_text3">({{groupList.length}})</span>
          </div>
          <div @click="handleItem({id:-1})" 
            class="w_full wl_item commhover flex aligncenter mb-6 f-14"
            :class="{active:activeId==-1}">
            <svg-icon class-name="mr-8 f-14" icon-class="icontent" />
            <span class="wl_text">未分组</span>
            <span class="pl-8 c_text3">(0)</span>
          </div> -->
          <div
            v-for="(item, index) in groupList"
            :key="index"
            class="w_full wl_item commhover flexbetween mb-6 f-14"
            @click="handleItem(item)"
            :class="{active:item.id == activeId}"
          >
            <div class="flex aligncenter l_item">
              <!-- <svg-icon class-name="mr-10 f-12" icon-class="ilist" /> -->
              <svg-icon v-if="index<2" class-name="mr-8 f-14" icon-class="icontent" />
              <svg-icon v-else class-name="mr-10 f-14 c_text4" icon-class="sort" />
              <span class="wl_text">{{item.groupName||'-'}}</span>
              <span class="pl-8 c_text3">({{item.groupAccountNumber}})</span>
            </div>
            <div>
              <el-dropdown v-if="index>=2" @command="handleCommand($event,item)">
                <!-- <i class="el-icon-more f-12 c_text3"></i> -->
                <svg-icon class-name="f-14" icon-class="ipmore" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="a" v-if="index >= 3">置顶</el-dropdown-item>
                  <el-dropdown-item command="b" v-hasPermi="['system:tgwechat:editgroup']">修改名称</el-dropdown-item>
                  <el-dropdown-item command="c" v-hasPermi="['system:tgwechat:deletegroup']">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- <i class="el-icon-more f-12 c_text3"></i> -->
            </div>
          </div>
        </div>
      </div>
      <div class="wc_right bg_fff">
        <div class="p-12 flexbetween">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item>
              <el-button
                v-hasPermi="['system:tgwechat:add']"
                class="f-14 f14btn"
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleAddLogin"
              >
                企微号
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryParams.status"
                @change="handleQuery"
                style="width: 120px"
                placeholder="登录状态"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="clientUserName">
              <el-input
                v-model="queryParams.clientUserName"
                placeholder="管理员工"
                clearable
                style="width: 120px"
                @keyup.enter.native="handleQuery"
                suffix-icon="el-icon-search"
              />
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryParams.companyId"
                @change="handleQuery"
                style="width: 200px"
                placeholder="选择企业"
                clearable
              >
                <el-option
                  v-for="item in qyOptions"
                  :key="item.company_id"
                  :label="item.company_name"
                  :value="item.company_id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="nickname">
              <el-input
                v-model="queryParams.nickname"
                placeholder="搜索企微号"
                clearable
                style="width: 180px"
                @keyup.enter.native="handleQuery"
                suffix-icon="el-icon-search"
              />
            </el-form-item>
            <!-- <el-form-item>
              <el-select
                v-model="queryParams.status"
                @change="handleQuery"
                style="width: 120px"
                placeholder="端口"
              >
                <el-option
                  v-for="item in portOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item> -->
          </el-form>
          <div class="flex aligncenter mb-18">
            <el-button
              v-hasPermi="['system:tgwechat:removegroup']"
              :disabled="multiple"
              type="primary"
              size="small"
              class="f-14 f14btn ml-8"
              plain
              @click="handleOpenGroup"
              >换分组</el-button
            >
            <el-button
              plain
              size="small"
              class="f-14 f14btn"
              @click="handleDelete"
              v-hasPermi="['system:tgwechat:export']"
            >
              <svg-icon class-name="mr-10 f-12" icon-class="iexport" />
              导出数据
            </el-button>
          </div>
        </div>
        <el-table
          v-loading="loading"
          class="commtable"
          :data="tableList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="75" fixed align="center" />
          <el-table-column label="企微号" width="300px" prop="userName">
            <template slot-scope="scope">
              <div class="flex">
                <img
                  :src="scope.row.headImgUrl"
                  alt=""
                  class="iavatar"
                />
                <div class="ml-12">
                  <div class="c_222333 accounttext flex aligncenter">
                    <div class="mr-6">{{ scope.row.nickname }}</div>
                    <i class="el-icon-edit c_primary mr-6 commhover" @click="handleWechatInfo(scope.row)"></i>
                    <i class="el-icon-refresh-right c_primary commhover" @click="handleSynch(scope.row)"></i>
                  </div>
                  <div class="c_f90 mt-4 accounttext">@{{scope.row.companyName}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="员工编号"
            min-width="200"
            prop="wxid"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="分组"
            prop="phonenumber"
            min-width="200"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.groupName || "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="120" prop="phonenumber">
            <template slot-scope="scope">
              <span class="dot mr-6" :class="scope.row.status==1?'bg_52c41a':'bg_888999'"></span>
              <span :class="scope.row.status==1?'c_52c41a':'c_888999'">{{ scope.row.status==1?"在线":"离线" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="客户数/群数"
            min-width="160"
            prop="phonenumber"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.num || 0 }} / {{ scope.row.num || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="管理员工"
            prop="clientUserName"
            min-width="200"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="操作"
            fixed="right"
            min-width="160px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button  v-if="scope.row.status==1"
                type="danger"
                v-hasPermi="['system:tgwechat:unlogin']"
                @click="handleDownLine(scope.row)"
                size="mini"
                >下线</el-button
              >
              <el-button v-else
                v-hasPermi="['system:tgwechat:login']"
                type="primary"
                @click="handleLoginRow(scope.row)"
                size="mini"
                >登录</el-button
              >
              <el-dropdown @command="handleMore($event, scope.row)">
                <el-button size="mini">更多操作</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['system:tgwechat:records']" command="a">登录记录</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:tgwechat:removegroup']"  command="b">移动分组</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:tgwechat:delete']" command="c">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          class="qwbpagination flexcenter"
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
          layout="prev,pager,next"
        />
      </div>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="0">
        <el-form-item label="" prop="groupName">
          <el-input
            v-model="form.groupName"
            size="small"
            maxlength="10"
            show-word-limit
            placeholder="请输入分组名称，不超过10个字"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="新企微号登录"
      :visible.sync="typeOpen"
      width="580px"
      :before-close="handleCloseType"
      :close-on-click-modal='false'
    >
      <template v-if="logintype == 1">
        <div class="loginitem p-12 active mb-12">
          <div class="f-18 c_text2 fw-6 mb-4">我已登录过</div>
          <div class="f-14 c_text3 mb-12">
            如果您的企微号之前在当前（子）账号下已经登录过，请直接在管理企微号的列表里点击登录！
          </div>
          <el-button size="small" type="primary" @click="handleCloseType"
            >返回企微号列表登录</el-button
          >
        </div>
        <div class="loginitem p-12">
          <div class="f-18 c_text2 fw-6 mb-4">我没有登录过</div>
          <div class="f-14 c_text3 mb-12">
            扫码登录需要重新分配新的服务器，请先核实您的企微号未曾在当前（子）账号登录过，避免出现安全隐患！新号登录需同步数据请稍后使用。
          </div>
          <el-button size="small" type="primary" plain @click="handleOpenLogin"
            >没有登录过，新号扫码登录</el-button
          >
        </div>
      </template>
      <!-- <div v-if="logintype == 2">
        <div class="fw-6 f-16 c_text2 mb-20">请选择托管的端口类型：</div>
        <el-select v-model="portType" placeholder="请选择" size="small" style="width:400px">
          <el-option
            v-for="item in portTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <span v-if="logintype == 2" slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleOpenLogin">下一步</el-button>
        <el-button size="small" @click="handleCloseType">取消</el-button>
      </span> -->
    </el-dialog>
    <!--  登录  -->
    <!--       :typeOpen="2"
      width="380px" -->
    <wechat-login
      v-if="loginopen"
      :visable="loginopen"
      @close="handleCloseLogin"
      @success='handleScanSuccess'
    />
    <!-- 单个登录 -->
    <!-- <wechat-login-row
      v-if="loginrowopen"
      :visable="loginrowopen"
      @close="handleCloseRowLogin"
    /> -->
    <!-- 登录记录 -->
    <login-record
      v-if="recodeopen"
      :visable.sync="recodeopen"
      @close="handleCloseRecode"
    />
    <!-- 移动分组 -->
    <remove-group
      v-if="removeopen"
      :visable.sync="removeopen"
      @success='getList'
    />
    <!-- @close="handleCloseGroup" -->
    <!-- 没有席位 -->
    <!-- <login-no-seat v-if="noseatopen" :visable.sync="noseatopen" /> -->
    <!--  -->
    <yzm-code v-if="yzmopen" :uuid='uuid' :visable.sync="yzmopen" @success='getList' />


    <!-- 企微号信息 -->
    <wechat-info
      v-if="infoopen"
      :visable="infoopen"
      :row='rowitem'
      @close="handleCloseInfo"
    />
  </div>
</template>
<script>
import WechatLogin from "./WechatLogin.vue";
import WechatLoginRow from "./WechatLoginRow.vue";
import LoginRecord from "./LoginRecord.vue";
import RemoveGroup from "./RemoveGroup.vue";
import LoginNoSeat from "./components/LoginNoSeat.vue";
import YzmCode from "./components/YzmCode.vue";
import WechatInfo from "./components/WechatInfo.vue";
import { listGroup, addGroup,updateGroup,deleteGroup, topGroup, listAccount, offAccount, deleteAccount  } from '@/api/system/tgwechat'
import { getCompany } from '@/api/comm'
export default {
  data() {
    return {
      groupList:[],
      activeId:'',
      statusOptions: [
        { id: 1, name: "全部" },
        { id: 2, name: "离线" },
        { id: 3, name: "在线" },
      ],
      qyOptions: [
        // { id: 1, name: "云涌传媒" },
        // { id: 2, name: "锐行科技" },
      ],
      portOptions:[
        { id: 1, name: "aPad" },
        { id: 2, name: "iPad" },
        { id: 3, name: "Win" },
      ],
      logintype:1,
      portType:1,
      portTypeList:[
        {value:1,label:'aPad【使用AndroidPad客户端】'},
        {value:2,label:'iPad【使用iPad客户端】'},
        {value:3,label:'Win【使用Windows客户端】'},
      ],
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId:'',
        companyId:'',
        nickname:'',
        clientUserName:''
      },
      total: 0,
      tableList: [
        // { id: 1, username: "Garmary" }
      ],
      title: "",
      open: false,
      form: {},
      rules: {},
      typeOpen: false,
      loginopen: false,
      multiple: true,
      rowIds: [],
      loginrowopen: false,
      recodeopen: false,
      removeopen: false,
      noseatopen: false,
      yzmopen: false,
      uuid:'',
      infoopen:false,
      rowitem:null,
    };
  },
  components: {
    WechatLogin,
    WechatLoginRow,
    LoginRecord,
    RemoveGroup,
    LoginNoSeat,
    YzmCode,
    WechatInfo
  },
  created(){
    // 分组
    this.getGroupList()
    // 公司列表
    this.getCompany()
  },
  methods: {

    getGroupList(){
      listGroup().then(res=>{
        this.groupList = res.data
        if(this.groupList.length){
          this.handleItem(this.groupList[0])
          this.getList()
        }
      })
    },

    getList(){
      this.loading = true
      listAccount(this.queryParams).then(res=>{
        this.tableList = res.rows.map(item=>({...item,status:1}))
        this.total = res.total
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },

    getCompany(){
      getCompany().then(res=>{
        this.qyOptions = res.data
      })
    },

    handleSynch(item){
      this.$message.success('同步成功')
    },

    handleItem(item){
      this.queryParams.groupId = item.id
      this.activeId = item.id
      this.getList()
    },

    handleAdd() {
      this.title = "添加分组";
      this.resetForm()
      this.open = true;
    },

    resetForm(){
      this.form = {
        id:undefined,
        groupName:undefined,
      }
    },

    handleClose() {
      this.open = false;
    },

    handleCommand(command,item) {
      // console.log(command)
      switch (command) {
        case "a":
          this.handleTop(item);
          break;
        case "b":
          this.title = "修改分组";
          this.resetForm()
          console.log('item:', item)
          this.form.id = item.id;
          this.form.groupName = item.groupName
          this.open = true;
          break;
        case "c":
          this.handleDelete(item);
          break;
        default:
          break;
      }
    },

    handleTop(item){
      let arr = JSON.parse(JSON.stringify(this.groupList))
      arr.splice(0,2);
      let index = -1
      arr.forEach((i,iv)=>{
        if(i.id == item.id){
          index = iv
        }
      })
      console.log('arr1:', arr,index)
      arr.unshift(arr.splice(index, 1)[0]);
      console.log('arr2:', arr)
      let params = arr.map((aitem,aindex)=>({id:aitem.id,groupOrderIndex:aindex+1}))
      topGroup(params).then(res=>{
        this.$message({ type: "success", message: "置顶成功!"});
        this.getGroupList()
      })
    },

    handleDelete(item) {
      this.$confirm("确定删除分组？", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        iconClass: "el-icon-warning-outline",
        type: "warning",
      })
        .then(() => {
          deleteGroup(item.id).then(res=>{
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getGroupList()
          })
          
        })
        .catch(() => {});
    },

    handleDownLine(row) {
      // this.$modal.confirm('确认清空本页黑名单？').then(function () {
      //   return delUser(userIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {
      // });
      this.$msgBox
        .showMsgBox({
          title: "是否确认下线？",
          content:
            "该企微号正在执行某些托管方案下的操作，下线会导致部分功能无法正常使用，请谨慎操作。",
        })
        .then(async (val) => {
          offAccount({id:row.id}).then(()=>{
            this.$message({
              type: "success",
              message: "下线成功!",
            });
            this.getList()
          })
        })
        .catch(() => {});
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        if(this.form.id){
          // 修改
          updateGroup(this.form).then(res=>{
            this.$message.success('修改成功');
            this.handleClose();
            this.getGroupList()
          })
        }else{
          addGroup(this.form).then(res=>{
            this.$message.success('添加成功');
            this.handleClose();
            this.getGroupList()
          })
        }

      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.rowIds = selection.map((item) => item.userId);
      this.multiple = !selection.length;
    },

    handleAddLogin() {
      this.logintype = 1
      this.typeOpen = true;
    },

    handleCloseType() {
      this.typeOpen = false;
    },

    handleChangeType(){
      this.logintype = 2
    },

    handleOpenLogin() {
      this.handleCloseType();
      this.loginopen = true;
      // this.noseatopen = true;
    },

    handleCloseLogin() {
      this.loginopen = false;
    },

    handleScanSuccess(uuid){
      if(uuid){
        this.uuid = uuid
        this.yzmopen = true
      }else{
        this.getList()
      }
      this.handleCloseLogin()
      
    },

    // 单个登录
    handleLoginRow(row) {
      console.log(row);
      this.loginrowopen = true;
    },
    handleCloseRowLogin() {
      this.loginrowopen = false;
    },

    handleWechatInfo(item){
      this.rowitem = item
      this.infoopen = true
    },

    handleCloseInfo(){
      this.infoopen = false
    },

    // 更多操作
    handleMore(type, row) {
      switch (type) {
        case "a":
          // 登录记录
          this.recodeopen = true;
          break;
        case "b":
          // 移动分组
          this.handleOpenGroup();
          break;
        case "c":
          // 删除
          this.handleDeteleTable(row);
          break;
        default:
          break;
      }
    },

    // 关闭登录记录
    handleCloseRecode() {
      this.recodeopen = false;
    },

    // 移动分组
    handleOpenGroup() {
      this.removeopen = true;
    },
    // handleCloseGroup() {
    //   this.removeopen = false;
    // },

    handleDeteleTable(row) {
      this.$msgBox
        .showMsgBox({
          title: "是否确认删除？",
          content:
            "该企微号正在执行服务，删除将会使该号从操作中释放，导致部分功能无法正常使用，请谨慎选择。*如该号已加入在线聊天，成功删除后，聊天记录会被一并删除，重新登录后无法恢复。",
        })
        .then(() => {
          deleteAccount(row.id).then(()=>{
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      //   this.$confirm("是否确认删除？", "", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     showClose: false,
      //     type: "warning",
      //   })
      //     .then(() => {
      //       this.$message({
      //         type: "success",
      //         message: "删除成功!",
      //       });
      //     })
      //     .catch(() => {
      //       this.$message({
      //         type: "info",
      //         message: "已取消删除",
      //       });
      //     });
    },
  },
};
</script>
<style lang="scss" scoped>
.wc_top {
  border-radius: 4px;
}
.wc_wraaper {
  flex: 1;
  justify-content: flex-start;
  align-items: flex-start;
}
.wc_left {
  width: 240px;
  border: 1px solid #e9e9e9;
  margin-right: 12px;
}
.wl_header {
  height: 56px;
  padding: 0 12px 0 20px;
  border-bottom: 1px solid #e9e9e9;
}
.wl_content {
  height: calc(100vh - 258px);
  overflow-y: auto;
}
.wl_item {
  padding: 8px 12px;
  border-radius: 4px;
  line-height: 24px;

  &.active {
    background-color: #ebf2ff;
  }
  &:hover {
    background-color: #f0f0f0;
  }
  // .el-icon-more {
  //   display: none;
  // }
  // &:hover .el-icon-more {
  //   display: inline-block;
  // }
}
.wl_text {
  display: inline-block;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.plusbtn {
  border: 1px solid #e9e9e9;
}
.wc_right {
  width: calc(100% - 250px);
  flex: 1;
  border: 1px solid #e9e9e9;
  overflow: auto;
}
.l_item {
  width: 86%;
}
.iavatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
}
.accounttext {
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  i{
    display: none;
  }
  &:hover{
    i{
      display: inline-block;
    }
  }
}
.dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
}
.loginitem {
  border: 1px solid #e9e9e9;
  &.active {
    background: #e0eaff;
    border: 1px solid #a2beff;
  }
}
.qwbpagination {
  padding: 20px !important;
}
</style>